<?php

class DefaultController extends BackendController
{
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            //'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */

    public function accessRules() {
        return array(
            array(
                'allow',
                'actions' => array('index', 'main', 'logout'),
                'users' => array('@')
            ),
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'captcha', 'error'),
                'users' => array('*'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * @var string the default layout for the controller view. Defaults to '//layouts/column1',
     * meaning using a single column layout. See 'protected/views/layouts/column1.php'.
     */
    public $layout=false;

	public function actionIndex()
	{
		$this->render('index');
	}

	//Dashboard
    public function actionMain()
    {
        //获取数据库版本号
        //var_dump(Yii::app()->db->createCommand()->select('version()')->queryRow()["version()"]);exit;
        switch (Yii::app()->getDb()->driverName) {
            case "mysql":
                $dbInfo = 'MySQL ' . Yii::app()->db->createCommand()->select('version()')->queryRow()["version()"];
                break;
            case "pgsql":
                $dbInfo = Yii::app()->db->createCommand()->select('version()')->queryRow()["version()"];
                break;
            default:
                $dbInfo = "Unknown";
        }
        $info = array(
            'OPERATING_ENVIRONMENT' => PHP_OS . ' ' . $_SERVER['SERVER_SOFTWARE'],
            'PHP_RUN_MODE' => php_sapi_name(),
            'DB_INFO' => $dbInfo,
            'UPLOAD_MAX_FILE_SIZE' => ini_get('upload_max_filesize'),
            'MAX_EXECUTION_TIME' => ini_get('max_execution_time') . "s"
        );
        $obj = new ServerInfo();
        $serverInfo = $obj->getinfo();
        $status = array(
            'DISK_SPACE' => array(
                'NUM' => ceil( $serverInfo['diskTotal'] - $serverInfo['freeSpace'] ) . 'G' . ' / ' . ceil($serverInfo['diskTotal']) . 'G',
                'PERCENTAGE' => (floatval($serverInfo['diskTotal']) != 0) ? round(($serverInfo['diskTotal'] - $serverInfo['freeSpace']) / $serverInfo['diskTotal'] * 100, 2) : 0,
            ),
            'MEM' => array(
                'NUM' => $serverInfo["UsedMemory"] . ' / ' . $serverInfo['TotalMemory'],
                'PERCENTAGE' => $serverInfo["memPercent"],
            ),
            'REAL_MEM' => array(
                'NUM' => $serverInfo["memRealUsed"] . "(Cached {$serverInfo['CachedMemory']})" . ' / ' . $serverInfo['TotalMemory'],
                'PERCENTAGE' => $serverInfo['memRealPercent'] . '%',
            ),
        );
        $temp = [
            'ARTICLE' => Article::model()->find('type=:type',array(':type'=>Article::ARTICLE))->count('id'),
            'COMMENT' => count(Comment::model()->findAll()),
            'USER' => User::model()->find()->count('id'),
            'FRIEND_LINK' => FriendlyLink::model()->find()->count('id'),
        ];

        $articleCommand = Yii::app()->db->createCommand()->from('fcms_article')->where('created_at BETWEEN :startTime AND :endTime', [':startTime' => strtotime(date('Y-m-01')), ':endTime' => strtotime(date('Y-m-01 23:59:59') . " +1 month -1 day")])->queryScalar();
        $commentCommand = Yii::app()->db->createCommand()->from('fcms_comment')->where('created_at BETWEEN :startTime AND :endTime', [':startTime' => strtotime(date('Y-m-d 00:00:00')), ':endTime' => time()])->queryScalar();
        $userCommand = Yii::app()->db->createCommand()->from('fcms_user')->where('created_at BETWEEN :startTime AND :endTime', [':startTime' => strtotime(date('Y-m-01')), ':endTime' => strtotime(date('Y-m-01 23:59:59') . " +1 month -1 day")])->queryScalar();
        $friendlyLinkCommand = Yii::app()->db->createCommand()->from('fcms_friendly_link')->where('created_at BETWEEN :startTime AND :endTime', [':startTime' => strtotime(date('Y-m-01')), ':endTime' => strtotime(date('Y-m-01 23:59:59') . " +1 month -1 day")])->queryScalar();
        //var_dump($articleCommand);exit;
        $percent = '0.00';
        $statics = [
            'ARTICLE' => [
                $temp['ARTICLE'],
                $temp['ARTICLE'] ? number_format($articleCommand / $temp['ARTICLE'] * 100, 2) : $percent
            ],
            'COMMENT' => [
                $temp['COMMENT'],
                $temp['COMMENT'] ? number_format($commentCommand / $temp['COMMENT'] * 100, 2) : $percent
            ],
            'USER' => [
                $temp['USER'],
                $temp['USER'] ? number_format($userCommand / 1 * 100, 2) : $percent
            ],
            'FRIEND_LINK' => [
                $temp['FRIEND_LINK'],
                $temp['FRIEND_LINK'] ? number_format($friendlyLinkCommand / $temp['FRIEND_LINK'] * 100, 2) : $percent
            ],
        ];
        //$comments = BackendComment::getRecentComments(6);

        $this->render('main',
            array(
                'info' => $info,
                'status' => $status,
                'statics' => $statics
            )
        );
    }


    public function actionError()
    {
        if($error=Yii::app()->errorHandler->error)
        {
            if(Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the login page
     */
    public function actionLogin()
    {
        $model=new LoginForm();
        //echo md5('admin');

        // if it is ajax validation request
        if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if(isset($_POST['LoginForm']))
        {
            $model->attributes=$_POST['LoginForm'];
            //echo md5($_POST['LoginForm']['password']);
            // validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login()){
                Yii::app()->session['loginTime'] = time(); //存储session时间
                Yii::app()->user->setFlash('success', '登陆成功');  // success是标识符
                $this->redirect(array('default/index'));
            }
        }
        // display the login form
        $this->render('login',array('model'=>$model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        //$this->redirect(Yii::app()->homeUrl);//返回首页
        $this->redirect(array('default/login'));//返回登陆页
    }

    /**
     * 验证码
     * @return array
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
                'fontFile' =>  ROOT_PATH.'/resource/backend/fonts/Britanic.ttf', //自定义字体
                'height'=>'32',
                'width'=>'90',
                'minLength'=>'4',
                'maxLength'=>'5',
                'offset' => 2,    //字符间距
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }



}